package com.yanxin.credit.service;

import com.yanxin.credit.enums.MinioBucketEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class FileService {


    @Autowired
    private MinIoService minIoService;


    public Object uploadFile(MultipartFile uploadFile, String type) throws IOException {

        int ran2 = (int) (Math.random() * (100 - 1) + 1);
        String fileName = String.valueOf(System.currentTimeMillis()) + ran2;

        String originUploadName = uploadFile.getOriginalFilename();
        String suffix = originUploadName.substring(originUploadName.lastIndexOf("."));
        if (suffix.endsWith(".html") || suffix.endsWith(".exe") || suffix.endsWith(".jsp")) {
            throw new IllegalStateException("禁止上传的文件类型");
        }
        // 原文件名
        final String originalFilename = uploadFile.getOriginalFilename();
        String bucketName = MinioBucketEnum.getType(type).getValue();
        String uploadFileName = fileName + originalFilename.substring(originalFilename.lastIndexOf("."));
        minIoService.putObject(bucketName, uploadFileName,
                uploadFile.getInputStream());
        /*final String uploadFileName = minIoService.putObjectForContent(
                fileName + originalFilename.substring(originalFilename.lastIndexOf("."))
                , type, uploadFile.getInputStream(), bucketName);*/

        String url = minIoService.getObjectUrl(bucketName, uploadFileName, 200);
        Map<String, Object> map = new HashMap<>(8);
        // 临时使用地址
        map.put("fileUrl", url);
        // minio 桶名称以及文件名,用来保存
        map.put("objectName", uploadFileName);
        return map;
    }
}
